# -*- coding: utf-8 -*-
# --------------------------------------
# @Time    : 2025/6/20 10:57
# @File    : db.py.py
# @Project : Practice_flask_0619
# @Author  : CHH
# @Desc    : Windows   文件描述
# @Copyright : © 2025 HORDOR . All rights reserved.
# @Version : 1.0.0
# --------------------------------------
import pymysql
from dbutils.pooled_db import PooledDB
from pymysql import cursors
from config import settings

DB_POOL = PooledDB(
    creator=pymysql,
    mincached=2,
    maxcached=3,
    maxconnections=20,
    host=settings.HOST,
    port=3306,
    user=settings.USER,
    passwd=settings.PASSWD,
    blocking=True,
    setsession=[],
    ping=0,
    db=settings.DB,
    charset='utf8',
)


def fetch_one(sql, params):
    conn = DB_POOL.connection()
    cursor = conn.cursor(cursor=cursors.DictCursor)
    cursor.execute(sql, params)
    result = cursor.fetchone()
    cursor.close()
    conn.close()
    return result

def fetch_all(sql, params):
    conn = DB_POOL.connection()
    cursor = conn.cursor(cursor=cursors.DictCursor)
    cursor.execute(sql, params)
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result

def reset_one(sql,params):
    conn = DB_POOL.connection()  # 连接池的形式，进行数据库连接。
    cursor = conn.cursor(cursor=cursors.DictCursor)  # 如果是这个返回的j将是字典
    cursor.execute(sql, params)
    affected_rows = cursor.rowcount
    conn.commit()
    cursor.close()
    conn.close()  # 此时不是关闭连接了，而是将连接交还连接池中。
    # 返回插入的行id
    return affected_rows

def insert_one(sql,params):
    conn = DB_POOL.connection()  # 连接池的形式，进行数据库连接。
    cursor = conn.cursor(cursor=cursors.DictCursor)  # 如果是这个返回的j将是字典
    cursor.execute(sql, params)
    conn.commit()
    cursor.close()
    conn.close()  # 此时不是关闭连接了，而是将连接交还连接池中。
    # 返回插入的行id
    return cursor.lastrowid